package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.LikesService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-23 9:13
 */
@Service
@Slf4j
public class LikesServiceImpl implements LikesService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public void likes(LikesBehaviorDto dto) {
        //1.校验用户登陆状态
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null || user.getId() == null){
            //未登录
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.存储点赞数据 set
        String userId = user.getId().toString();
        String articleId = dto.getArticleId().toString();

        BoundSetOperations<String, String> set = stringRedisTemplate.boundSetOps(BehaviorConstants.LIKE_BEHAVIOR + articleId);

        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        if(dto.getOperation() == 0){
            //点赞
            //判断是否点赞
            Boolean member = set.isMember(userId);
            if(member != null && member){
                //已经存在
                throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
            }
            //写入点赞数据
            set.add(userId);
            updateArticleMess.setAdd(1);
        }else if(dto.getOperation() == 1){
            //取消点赞
            Boolean member = set.isMember(userId);
            if(member != null && !member){
                //已经存在
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //删除数据
            set.remove(userId);
            updateArticleMess.setAdd(-1);
        }

        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_BEHAVIOR_KAFKA_TOPIC,
                JSON.toJSONString(updateArticleMess));
    }
}
